package com.biwei.app.wrap.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * feign request interceptor
 */
@Component
public class CookieInterceptor implements RequestInterceptor,HandlerInterceptor {
    private static final ThreadLocal<String> CookieLocal = new ThreadLocal<>();
    private static final ThreadLocal<Collection<String>> CookieSetLocal = new ThreadLocal<>();
    public static void setCookieSet(Collection<String> cookie) {
        CookieSetLocal.set(cookie);
    }
    @Override
    public void apply(RequestTemplate template) {
        if (CookieLocal.get() != null) {
            template.header("Cookie", CookieLocal.get());
        }
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String cookie = request.getHeader("Cookie");
        if (!StringUtils.isEmpty(cookie)) {
            CookieLocal.set(cookie);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        if (CookieSetLocal.get() != null) {
            CookieSetLocal.get().stream().forEach(e -> response.addHeader("set-cookie", e));
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        CookieLocal.remove();
        CookieSetLocal.remove();
    }
}
